package com.ksl.kinglockguard.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ksl.kinglockguard.data.Constants;
import com.lsk.open.core.MyLog;

public class DeleteSdCacheUtil extends Thread {

	List<FileItem> mList = new ArrayList<FileItem>();
	private long mTotalSize;
	private long currentTime = System.currentTimeMillis();
	final static long TWO_DAY = 48 * 60 * 60 * 1000;
	private boolean isDeleteJust=false;

	
	public DeleteSdCacheUtil(boolean isDeleteJust) {
		super();
		this.isDeleteJust = isDeleteJust;
	}

	@Override
	public void run() {
		try {
			if(!isDeleteJust)
			Thread.sleep(10 * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		if (isDeleteJust||isCacheOverLimit()) {
			readFileDir(Constants.FOLDER_ROOT);
			if (isDeleteJust||(mTotalSize > 200 * 1048576)) {
				for (FileItem item : mList) {
					if (isDeleteJust||(item.modifyTime + TWO_DAY < currentTime)) {
						File file = new File(item.path);
						MyLog.i("ydy","SdcardMonitor  mTotalSize=="+mTotalSize+" time=="+new Date(item.modifyTime).toString());
						if (file.exists())
							file.delete();
					}
				}
			}
			mList.clear();
		}

		super.run();
	}

	public DeleteSdCacheUtil() {
		super();
		mTotalSize = 0;
	}

	private boolean isCacheOverLimit() {
		File file = new File(Constants.FOLDER_PICTURE);
		if (file.exists()) {
			File[] files = file.listFiles();
			if (files != null) {
				if (files.length > 10)
					return true;
			}
		}
		return false;

	}

	private void readFileDir(String path) {
		File file = new File(path);
		if (file.exists()) {
			File[] files = file.listFiles();
			if (files == null)
				return;
			for (int i = 0; i < files.length; i++) {
				File tmp = files[i];
				if (tmp.isFile()) {
					mTotalSize += tmp.length();
					FileItem item = new FileItem(tmp.getAbsolutePath(),
							tmp.length(), tmp.lastModified());
					mList.add(item);
				} else {
					readFileDir(tmp.getAbsolutePath());
				}

			}

		}
	}

	static class FileItem {

		public FileItem(String path, long size, long modifyTime) {
			super();
			this.path = path;
			this.size = size;
			this.modifyTime = modifyTime;
		}

		public String path;
		public long size;
		public long modifyTime;
	}

}
